//
//  AppDelegate_notification.swift
//  MyLibrary
//
//  Created by 周博 on 2020/6/18.
//  Copyright © 2020 ncit. All rights reserved.
//

import UIKit
import UserNotifications

open class BaseAppDelegate: UIResponder, UIApplicationDelegate {

    public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

}


/**
 * 本地或远程通知相关处理
 */
public extension BaseAppDelegate {


    /**
     * 注册本地通知
     */
    func registerNotification(userinfo: [String: String]) {

        let center = UNUserNotificationCenter.current()

        center.delegate = self

        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            print("grated : \(granted)")
        }

        //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        center.getNotificationSettings { (settings) in

        }

        self.pushNotification(alertTime: 2, userinfo: userinfo, title: "标题", body: "内容")

    }

    // 发送本地通知具体方法
    func pushNotification(alertTime: NSInteger, userinfo: [String: String], title: String, body: String) {

        let center: UNUserNotificationCenter = UNUserNotificationCenter.current()

        // 需创建一个包含待通知内容的 UNMutableNotificationContent 对象，注意不是 UNNotificationContent ,此对象为不可变对象。
        let content = UNMutableNotificationContent()

        content.title = title
        content.body = body

        content.userInfo = userinfo

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(alertTime), repeats: false)
        let request = UNNotificationRequest(identifier: "fivesecond", content: content, trigger: trigger)
        center.add(request, withCompletionHandler: nil)
    }
}



extension BaseAppDelegate: UNUserNotificationCenterDelegate {


    /**
     * 方法: ①
     *
     * 前台收到通知时即调用
     * 在接收到通知的回调方法中通过调用completionHandler, 通过控制其参数来控制通知是否允许alert, sound, badge
     * 前台收到通知的时候, 会立即调用这个方法, 当用户在前台点击了banner, 会调用下面的方法②
     *
     * 推送内容可以在userinfo里取得, userinfo是一个字典
     */
    public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent")
        completionHandler([.alert,.sound,.badge])
    }

    /**
     * 方法: ②
     *
     * 1. 后台点击通知调用 (点击时调用)
     * 2. 前台收到通知之后, 点击banner调用
     * 3. 方法里对于获取通知数据的处理要放在主线程, 否则可能会出现数据获取不及时, 导致界面异常的问题
     */
    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("didReceive")

        // 这里的处理方法最好切到主线程处理, 否则会出现一些问题

        DispatchQueue.main.async {
            let userinfo = response.notification.request.content.userInfo
        }
    }
}
